package com.tiancheng.trade.settlement.util;

import com.tiancheng.trade.commom.core.utils.DateTimeUtil;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * 自定义生成唯一单号工具类
 */
@Component
public class IdGenerateUtil {
    @Resource
    private RedissonClient redissonClient;

    public String getSettleLetterCode(){
        String dateStr = DateTimeUtil.format(LocalDateTime.now(), DateTimeUtil.yyyyMMdd);
        RAtomicLong rAtomicLong = redissonClient.getAtomicLong(dateStr);
        long incr = rAtomicLong.incrementAndGet();
        // 如果是当天第一个取号，就给key添加隔天失效时间
        if (incr == 1) {
            rAtomicLong.expireAsync(1, TimeUnit.DAYS);
        }
        return "T" + dateStr + String.format("%05d", incr);
    }

    public String getUniqueIDByKey(String key,String format,boolean expireFlag,TimeUnit timeUnit,Long num){
        RAtomicLong rAtomicLong = redissonClient.getAtomicLong(key);
        long incr = rAtomicLong.incrementAndGet();
        if(expireFlag && incr == 1){
            rAtomicLong.expireAsync(num, timeUnit);
        }
        return String.format(format, incr);
    }

}
